package cn.jinjimi.app.main.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import cn.jinjimi.app.controller.AccountController;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.DESEncryptUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.TimeCount;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.ForgetPswValidCheckEvent;
import cn.jinjimi.domain.data.dto.VerifyResultDTO;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.UserStore;
import cn.jinjimi.app.main.dialog.VerifyCodeDialog;
import cn.jinjimi.app.main.widget.MTextWatcher;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.PhoneBaseEditTextView;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.InputStream;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;
import okhttp3.Headers;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 *
 * @author zhenhua
 */
public class ForgetPswFragment extends BaseFragment implements View.OnClickListener {
    private PhoneBaseEditTextView phone;
    private Button cleanPhone;
    private EditText valid;
    private Button cleanValid;
    private TextView getValid;
    private TextView submit;
    private VerifyCodeDialog mDialog;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_forget_psw;
    }

    @Override
    protected void initial() {
        initView();
        initListener();

    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(R.string.title_retrieve_psw);
    }

    protected void initView() {
        //手机号
        phone = (PhoneBaseEditTextView) findView().findViewById(R.id.et_phone);
        phone.setHint(getString(R.string.prompt_find_psw_mobile));
        //清除手机号码
        cleanPhone = (Button) findView().findViewById(R.id.bt_clean_phone_number);
        //验证码
        valid = (EditText) findView().findViewById(R.id.valid_code);
        //清除验证码
        cleanValid = (Button) findView().findViewById(R.id.clean_valid_code);
        //获取验证码
        getValid = findView().findViewById(R.id.get_valid_code);
        //点击提交
        submit =  findView().findViewById(R.id.bt_submit);

        cleanPhone.setVisibility(StringUtils.isEmpty(phone.getText().toString()) ? View.GONE : View.VISIBLE);
    }

    protected void initListener() {
        cleanPhone.setOnClickListener(this);
        cleanValid.setOnClickListener(this);
        getValid.setOnClickListener(this);
        submit.setOnClickListener(this);

        phone.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 手机号框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanPhone.setVisibility(View.VISIBLE);
                } else {
                    cleanPhone.setVisibility(View.INVISIBLE);
                }
            }
        });
        valid.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 验证码框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanValid.setVisibility(View.VISIBLE);
                } else {
                    cleanValid.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_valid_code:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    getVerifyCaptcha(phone.getRealPhoneNum());
                }
                break;
            case R.id.bt_clean_phone_number:
                phone.setText("");
                break;
            case R.id.clean_valid_code:
                valid.setText("");
                break;
            case R.id.bt_submit:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    if (StringUtils.checkValidCode(getActivity(), valid)) {
                        submit();
                    }
                }
                break;
            default:break;
        }
    }

    /**
     * 提交请求
     */
    private void submit() {
        ((LoginActivity) getActivity()).showLoadingIndicator();
    }

    /**
     * 获取验证码
     *
     */
    private void getVerifyCaptcha(String mobile) {
        valid.requestFocus();
        AccountController
                .getCaptcha(mobile)
                .onSuccess(new Continuation<Boolean, Void>() {
                    @Override
                    public Void then(Task<Boolean> task) throws Exception {
                        if (task.getResult()) {
                            ToastUtil.showCusToast(getActivity(), "验证码已发送");
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onForgetPswValidCheckEvent(ForgetPswValidCheckEvent event) {
        switch (event.state) {
            case DataEvent.SUCC:
                if (checkActivityExit()) {
                    return;
                }
                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.content_fragment, ResetPswFragment.newInstance(event.data.getOperationToken()));
                ft.addToBackStack(null);
                ft.commit();

                break;
            case DataEvent.FAIL:
                if (checkActivityExit()) {
                    return;
                }
                ToastUtils.toastMessage(getActivity(), event.error);
                break;
            default:break;
        }
        ((LoginActivity) getActivity()).hideLoadingIndicator();
    }


    @Override
    public void onPause() {
        super.onPause();
        AndroidUtils.hideSoftKeyBoard(getActivity(), phone);
    }

    @Override
    public void onDestroyView() {
        if (mDialog != null) {
            mDialog.dismissDialog();
            mDialog = null;
        }
        super.onDestroyView();
    }
}
